package sqlplus;
import java.sql.*;
import java.io.*;

public class Lab16
{
	public static void main(String[] args){
	   if(args.length!=1){
	      System.out.println("用法:java Lab16 文件名");
	      return;
	   }
	   Connection con = null;
	   PreparedStatement ps = null;
	   ResultSet rs = null;
	   Blob blob = null;
	   int id = 1;
	   String fileName = args[0];
	   try{
		  con = JdbcUtil.getConn();
		  con.setAutoCommit(false);
		  //1.将blob对象读出来
		  String sql = "select FILE_CONTENT "+
			  "from t_blob where ID=?";
		  ps = con.prepareStatement(sql);
		  ps.setInt(1,id);
		  rs = ps.executeQuery();
		  if(rs.next()){
		    blob = rs.getBlob(1);
		  }
		  //2.将blob对象中的数据导入文件中
		  InputStream in = 
			  blob.getBinaryStream();
		  OutputStream out = 
			  new FileOutputStream(fileName);
		  int b = 0; int c = 0;
          while((b=in.read())!=-1){
		    out.write(b);
			if(++c%1024==0){
			   System.out.println("我们读了"+
			     c/1024+"kb...");
			}
		  }
          System.out.println("总共读了:"+
			  c/1024+"kb "+c%1024+"byte");
		  in.close();out.close();
		  con.commit();

	   }catch(Exception e){
	      e.printStackTrace();
		  try{
		    con.rollback();
		  }catch(Exception ex){
		    ex.printStackTrace();
		  }
	   }finally{
	      JdbcUtil.close(rs,ps,con);
	   }
	}
}
